import numpy as np
import pandas as pd
import jieba
import jieba.analyse
import sys
import networkx as nx
import json
import math

def draw_graph(corr_data):
    #corr_data =([['长安新能源', '小伟汽车', 0.217435489538873], ['长安新能源', '小王新能源', 0.104668819918697]])
    G1 = nx.Graph()
    existing_nodes = {}
    existing_edges = {}
    corr_data = [[x[0],x[1],1000*x[2]] for x in corr_data]
    #G1 = nx.MultiDiGraph()  # 有多重边有向图
    def build_graph_for_all():
        count=0
        for d in corr_data:
            if (count > 40) :
                return
            if d[0] not in existing_edges :
                G1.add_node(str(d[0]))
            if d[1] not in existing_edges :     
                G1.add_node(str(d[1]))
            #print(d[2])
            G1.add_weighted_edges_from([(str(d[0]),str(d[1]),d[2])])     
        count=count + 1
    build_graph_for_all()
    pos = nx.spring_layout(G1,weight='weight')
    #nx.draw(G1,pos=pos, width=2, with_labels=True)
    #pos=str(pos).replace("array(","").replace(")","").replace(" ","").replace("[","\"").replace("]","\"")
    list_coordinates = []
    
    for x in pos:
       dic_pos ={}
       dic_pos['name'] = x
       dic_pos['x']=pos.get(x)[0]
       dic_pos['y']=pos.get(x)[1]
       list_coordinates.append(dic_pos)
    
      
    return list_coordinates
    


def cal_cos(x,y):
    if len(x) <= 0 or len(x) != len(y):
        return 0
    res = np.array([[x[i] * y[i], x[i] * x[i], y[i] * y[i]] for i in range(len(x))])
    cos = sum(res[:, 0]) / (np.sqrt(sum(res[:, 1])) * np.sqrt(sum(res[:, 2])))
    if math.isnan(cos):
      cos = 0
    
    return cos

def main(argv):
    with open("stop_words.txt", "r" ,encoding='UTF-8') as f:  # 打开停用词文件
        stop_words = f.read()
    stop_words = stop_words.split('\n')
    r = str(argv[1:])
    r = r.replace("['","")
    r = r.replace("']","")
    r=r.strip("#")    #最后一位有分隔符的情况 #切类!切名
    #print(r)
    result = r.split("#")
    #print()
    #print(result)
    #print(str(len(result)))
    dic_words = {}
    dic_contents = {}
    #print(len(result))
    for x in result:
      name = x.split("!")[0]
      #print(x)
      #print()
      content = x.split("!")[1]
      #print(x.split("!"))
      #print()
      dic_contents[name]=content
      cut_words = [i for i in jieba.cut(content) if i not in stop_words]
      dic_words[name]=cut_words
      #for j in cut_words: 
        #dic_words[name]+=j
    #print(dic_words)
    jieba.analyse.set_stop_words("stop_words.txt")
    tags = jieba.analyse.extract_tags("。".join([dic_contents[k] for k in dic_contents]), topK=50)
    feature = tags #['动力电池','模块','固件','车辆','总成','控制','失控','连接','电动汽车','实用新型','芯片','电池','侦测','信号','电机','充电','灭火','控制器','信息','获取','传感器','状态','系统','碰撞检测','检测','汽车','障碍物','输出','路径','消防','单元','锁止','集成']
    #print(tags)
    feature_dic = {}
    for k in dic_words: 
        feature_vec = [0] * len(feature)
        for i in range(0,len(feature)): # 循环特征词
            for item in dic_words[k]: # 循环企业内的分词
                if item == feature[i]:
                    feature_vec[i] += 1
        feature_dic[k] = feature_vec
    company_list = list(feature_dic.keys()) # 车企列表
    cos_list = []
#print(feature_dic)
    max_relation=0;
    for i in range(0,len(company_list)):
        for j in range(i+1,len(company_list)):
            value = cal_cos(feature_dic[company_list[i]],feature_dic[company_list[j]])
            if abs(value)>max_relation:
              max_relation=value
            cos_list.append([company_list[i],company_list[j],value])
    #print('nodes……………………………………………………')
    #print(company_list)
    #print('lines……………………………………………………')
    #print(cos_list)
    #print(max_relation*0.2)
    delet = 0;
    leng = len(cos_list);
    for i in range(0,len(cos_list)):
      #print(cos_list[i])
      if abs(cos_list[i-delet][2])< (max_relation*0.1):
          #print("T")
          cos_list.pop(i-delet)
          delet+=1
          #cos_list.pop(i)
      
    
    #print(cos_list)       
    pos = draw_graph(cos_list)
    #print('coordinates……………………………………………………')
    #print(pos)
    list_lines= []
    for x in cos_list:
      dic_line={}
      dic_line['source']= x[0]
      dic_line['target']= x[1]
      if(pd.isnull(x[2])):
           x[2] = 0
      dic_line['value']= x[2]
      list_lines.append(dic_line)
    dic_json={}  ################
    dic_json['lines']=list_lines
    dic_json['coordinates']=pos
    #print(dic_json)
    json_string = json.dumps(dic_json,ensure_ascii=False)   
    print(json_string)
    return company_list, cos_list,pos  
      
    
   
    
   # print ("Length of list using naive method is : " + str(result))
  
if __name__ == '__main__':
    main(sys.argv)